<template>
  <div class="system-logs">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>系统日志</span>
          <div class="header-actions">
            <el-button type="primary" @click="refreshCurrentTab">
              刷新
            </el-button>
          </div>
        </div>
      </template>
      
      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <el-tab-pane label="数据导入记录" name="upload">
          <!-- 搜索栏 -->
          <div class="search-bar">
            <el-form :inline="true" :model="uploadSearchForm" class="search-form">
              <el-form-item label="文件名">
                <el-input v-model="uploadSearchForm.fileName" placeholder="请输入文件名" clearable />
              </el-form-item>
              <el-form-item label="数据类型">
                <el-select style="width: 120px" v-model="uploadSearchForm.dataType" placeholder="请选择数据类型" clearable>
                  <el-option label="收入信息" value="income" />
                  <el-option label="身份信息" value="identity" />
                  <el-option label="平台信息" value="platform" />
                </el-select>
              </el-form-item>
              <el-form-item label="状态">
                <el-select v-model="uploadSearchForm.status" placeholder="请选择状态" clearable>
                  <el-option label="处理中" :value="0" />
                  <el-option label="处理成功" :value="1" />
                  <el-option label="处理失败" :value="2" />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="searchUploadLogs">搜索</el-button>
                <el-button @click="resetUploadSearch">重置</el-button>
              </el-form-item>
            </el-form>
          </div>

          <el-table :data="uploadLogs" style="width: 100%" v-loading="uploadLoading">
            <el-table-column prop="id" label="ID" />
            <el-table-column prop="fileName" label="文件名" />
            <el-table-column prop="dataType" label="数据类型">
              <template #default="scope">
                <el-tag :type="getDataTypeTagType(scope.row.dataType)">
                  {{ getDataTypeLabel(scope.row.dataType) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="totalCount" label="总记录数" />
            <el-table-column prop="successCount" label="成功数" />
            <el-table-column prop="failCount" label="失败数" />
            <el-table-column prop="status" label="状态">
              <template #default="scope">
                <el-tag :type="getStatusTagType(scope.row.status)">
                  {{ getStatusLabel(scope.row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="uploadTime" label="上传时间" />
            <el-table-column label="操作" width="180">
              <template #default="scope">
                <el-button v-if="scope.row.errorMessage" size="small" @click="showError(scope.row)">
                  查看错误
                </el-button>
                <el-button size="small" type="danger" @click="deleteLog(scope.row.id, 'upload')">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="uploadPagination.current"
              v-model:page-size="uploadPagination.size"
              :page-sizes="[10, 20, 50, 100]"
              :total="uploadPagination.total"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleUploadSizeChange"
              @current-change="handleUploadCurrentChange"
            />
          </div>
        </el-tab-pane>
        
        <el-tab-pane label="API调用日志" name="api">
          <!-- 搜索栏 -->
          <div class="search-bar">
            <el-form :inline="true" :model="apiSearchForm" class="search-form">
              <el-form-item label="接口名称">
                <el-input v-model="apiSearchForm.apiName" placeholder="请输入接口名称" clearable />
              </el-form-item>
              <el-form-item label="状态">
                <el-select v-model="apiSearchForm.status" placeholder="请选择状态" clearable>
                  <el-option label="成功" :value="1" />
                  <el-option label="失败" :value="0" />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="searchApiLogs">搜索</el-button>
                <el-button @click="resetApiSearch">重置</el-button>
              </el-form-item>
            </el-form>
          </div>

          <el-table :data="apiLogs" style="width: 100%" v-loading="apiLoading">
            <el-table-column prop="id" label="ID" />
            <el-table-column prop="apiName" label="接口名称" />
            <el-table-column prop="apiUrl" label="接口地址" show-overflow-tooltip />
            <el-table-column prop="requestMethod" label="请求方法" />
            <el-table-column prop="responseCode" label="响应状态码" />
            <el-table-column prop="executionTime" label="执行时间(ms)" />
            <el-table-column prop="status" label="状态">
              <template #default="scope">
                <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
                  {{ scope.row.status === 1 ? '成功' : '失败' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="调用时间" />
            <el-table-column label="操作" width="180">
              <template #default="scope">
                <el-button size="small" @click="showApiDetail(scope.row)">
                  查看详情
                </el-button>
                <el-button size="small" type="danger" @click="deleteLog(scope.row.id, 'api')">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="apiPagination.current"
              v-model:page-size="apiPagination.size"
              :page-sizes="[10, 20, 50, 100]"
              :total="apiPagination.total"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleApiSizeChange"
              @current-change="handleApiCurrentChange"
            />
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    
    <!-- 错误详情对话框 -->
    <el-dialog v-model="errorDialogVisible" title="错误详情" width="60%">
      <div v-if="selectedError">
        <p><strong>文件名：</strong>{{ selectedError.fileName }}</p>
        <p><strong>错误信息：</strong></p>
        <el-input
          type="textarea"
          :rows="5"
          :value="formatErrorMessage(selectedError.errorMessage)"
          readonly />
      </div>
    </el-dialog>
    
    <!-- API详情对话框 -->
    <el-dialog v-model="apiDetailDialogVisible" title="API调用详情" width="80%">
      <div v-if="selectedApi" class="api-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="接口名称">{{ selectedApi.apiName }}</el-descriptions-item>
          <el-descriptions-item label="接口地址">{{ selectedApi.apiUrl }}</el-descriptions-item>
          <el-descriptions-item label="请求方法">{{ selectedApi.requestMethod }}</el-descriptions-item>
          <el-descriptions-item label="响应状态码">{{ selectedApi.responseCode }}</el-descriptions-item>
          <el-descriptions-item label="执行时间">{{ selectedApi.executionTime }}ms</el-descriptions-item>
          <el-descriptions-item label="调用时间">{{ selectedApi.createTime }}</el-descriptions-item>
        </el-descriptions>
        
        <el-divider />
        
        <el-row :gutter="20">
          <el-col :span="12">
            <h4>请求信息</h4>
            <div class="request-actions">
              <el-button 
                v-if="isTaxReportRequest(selectedApi.requestBody)"
                type="primary" 
                size="small" 
                @click="decryptRequestData(selectedApi.requestBody)"
                :loading="decryptLoading">
                解密请求数据
              </el-button>
            </div>
            <el-input
              type="textarea"
              :rows="8"
              :value="selectedApi.requestBody"
              readonly />
          </el-col>
          <el-col :span="12">
            <h4>响应信息</h4>
            <div class="response-actions" style="margin-bottom: 10px;">
              <el-button
                  v-if="isTaxReportResponse(selectedApi.responseBody)"
                  type="primary"
                  size="small"
                  @click="decryptResponseData(selectedApi.responseBody)"
                  :loading="decryptLoading">
                解密响应数据
              </el-button>
            </div>
            <el-input
                type="textarea"
                :rows="8"
                :value="selectedApi.responseBody"
                readonly />
          </el-col>
        </el-row>
        
        <el-divider v-if="selectedApi.errorMessage" />
        
        <div v-if="selectedApi.errorMessage">
          <h4>错误信息</h4>
          <el-input
            type="textarea"
            :rows="3"
            :value="selectedApi.errorMessage"
            readonly />
        </div>
      </div>
    </el-dialog>

    <!-- 解密结果对话框 -->
    <el-dialog v-model="decryptDialogVisible" title="解密结果" width="80%">
      <div v-if="decryptedContent" class="decrypt-result">
        <el-alert
          :title="`业务类型: ${decryptedContent.ywlx}`"
          type="info"
          :closable="false"
          style="margin-bottom: 20px;" />
        
        <el-tabs v-model="decryptActiveTab">
          <el-tab-pane label="格式化数据" name="formatted">
            <div v-if="decryptedContent.isJson">
              <el-input
                type="textarea"
                :rows="20"
                :value="formatJSON(decryptedContent.sjl)"
                readonly />
            </div>
            <div v-else>
              <el-alert
                title="数据不是有效的JSON格式"
                type="warning"
                :closable="false"
                style="margin-bottom: 20px;" />
              <el-input
                type="textarea"
                :rows="20"
                :value="decryptedContent.rawData"
                readonly />
            </div>
          </el-tab-pane>
          
          <el-tab-pane label="原始数据" name="raw">
            <el-input
              type="textarea"
              :rows="20"
              :value="decryptedContent.rawData"
              readonly />
          </el-tab-pane>
          
          <el-tab-pane label="数据信息" name="info">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="业务类型">{{ decryptedContent.ywlx }}</el-descriptions-item>
              <el-descriptions-item label="数据格式">{{ decryptedContent.isJson ? 'JSON' : '文本' }}</el-descriptions-item>
              <el-descriptions-item label="原始长度">{{ decryptedContent.rawData?.length || 0 }} 字符</el-descriptions-item>
              <el-descriptions-item label="解密状态">
                <el-tag type="success">成功</el-tag>
              </el-descriptions-item>
            </el-descriptions>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-dialog>



    <el-dialog v-model="decryptResponseDialogVisible" title="解密结果" width="80%">
      <div v-if="decryptedContent" class="decrypt-result">
        <el-tabs v-model="decryptActiveTab">
          <el-tab-pane label="格式化数据" name="formatted">
            <div v-if="decryptedContent.isJson">
              <el-input
                  type="textarea"
                  :rows="20"
                  :value="formatJSON(decryptedContent.sjl)"
                  readonly />
            </div>
            <div v-else>
              <el-alert
                  title="数据不是有效的JSON格式"
                  type="warning"
                  :closable="false"
                  style="margin-bottom: 20px;" />
              <el-input
                  type="textarea"
                  :rows="20"
                  :value="decryptedContent.rawData"
                  readonly />
            </div>
          </el-tab-pane>

          <el-tab-pane label="原始数据" name="raw">
            <el-input
                type="textarea"
                :rows="20"
                :value="decryptedContent.rawData"
                readonly />
          </el-tab-pane>

          <el-tab-pane label="数据信息" name="info">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="数据格式">{{ decryptedContent.isJson ? 'JSON' : '文本' }}</el-descriptions-item>
              <el-descriptions-item label="原始长度">{{ decryptedContent.rawData?.length || 0 }} 字符</el-descriptions-item>
              <el-descriptions-item label="解密状态">
                <el-tag type="success">成功</el-tag>
              </el-descriptions-item>
            </el-descriptions>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { systemLogApi } from '../api'
import { decryptTaxReportData, isEncryptedTaxData, formatJSON } from '../utils/decryptUtil'

const activeTab = ref('upload')
const uploadLogs = ref([])
const apiLogs = ref([])
const operationLogs = ref([])
const uploadLoading = ref(false)
const apiLoading = ref(false)
const operationLoading = ref(false)
const errorDialogVisible = ref(false)
const apiDetailDialogVisible = ref(false)
const decryptDialogVisible = ref(false)
const decryptResponseDialogVisible = ref(false)
const selectedError = ref(null)
const selectedApi = ref(null)
const selectedDecryptData = ref(null)
const decryptLoading = ref(false)
const decryptedContent = ref(null)

// 搜索表单
const uploadSearchForm = ref({
  fileName: '',
  dataType: '',
  status: ''
})

const apiSearchForm = ref({
  apiName: '',
  status: ''
})

const operationSearchForm = ref({
  username: '',
  operation: '',
  status: ''
})

// 分页配置
const uploadPagination = ref({
  current: 1,
  size: 20,
  total: 0
})

const apiPagination = ref({
  current: 1,
  size: 20,
  total: 0
})

const operationPagination = ref({
  current: 1,
  size: 20,
  total: 0
})

// 格式化错误信息，将分号替换为换行符
const formatErrorMessage = (errorMessage) => {
  if (!errorMessage) return ''
  return errorMessage.replace(/;/g, ';\n')
}

const handleTabClick = (tab) => {
  console.log('点击了标签：', tab.paneName)
  switch (tab.paneName) {
    case 'upload':
      loadUploadLogs()
      break
    case 'api':
      loadApiLogs()
      break
    case 'operation':
      loadOperationLogs()
      break
  }
}

// 数据导入记录相关方法
const loadUploadLogs = async () => {
  uploadLoading.value = true
  try {
    const params = {
      page: uploadPagination.value.current,
      size: uploadPagination.value.size,
      ...uploadSearchForm.value
    }
    
    const response = await systemLogApi.getUploadLogs(params)
    if (response.data.code === 200) {
      uploadLogs.value = response.data.data.records || []
      uploadPagination.value.total = response.data.data.total || 0
    } else {
      ElMessage.error(response.data.message || '获取数据导入记录失败')
    }
  } catch (error) {
    console.error('获取数据导入记录失败:', error)
    ElMessage.error('获取数据导入记录失败')
  } finally {
    uploadLoading.value = false
  }
}

const searchUploadLogs = () => {
  uploadPagination.value.current = 1
  loadUploadLogs()
}

const resetUploadSearch = () => {
  uploadSearchForm.value = {
    fileName: '',
    dataType: '',
    status: ''
  }
  uploadPagination.value.current = 1
  loadUploadLogs()
}

const handleUploadSizeChange = (size) => {
  uploadPagination.value.size = size
  uploadPagination.value.current = 1
  loadUploadLogs()
}

const handleUploadCurrentChange = (current) => {
  uploadPagination.value.current = current
  loadUploadLogs()
}

// API调用日志相关方法
const loadApiLogs = async () => {
  apiLoading.value = true
  try {
    const params = {
      page: apiPagination.value.current,
      size: apiPagination.value.size,
      ...apiSearchForm.value
    }
    
    const response = await systemLogApi.getApiLogs(params)
    if (response.data.code === 200) {
      apiLogs.value = response.data.data.records || []
      apiPagination.value.total = response.data.data.total || 0
    } else {
      ElMessage.error(response.data.message || '获取API调用日志失败')
    }
  } catch (error) {
    console.error('获取API调用日志失败:', error)
    ElMessage.error('获取API调用日志失败')
  } finally {
    apiLoading.value = false
  }
}

const searchApiLogs = () => {
  apiPagination.value.current = 1
  loadApiLogs()
}

const resetApiSearch = () => {
  apiSearchForm.value = {
    apiName: '',
    status: ''
  }
  apiPagination.value.current = 1
  loadApiLogs()
}

const handleApiSizeChange = (size) => {
  apiPagination.value.size = size
  apiPagination.value.current = 1
  loadApiLogs()
}

const handleApiCurrentChange = (current) => {
  apiPagination.value.current = current
  loadApiLogs()
}

// 操作日志相关方法
const loadOperationLogs = async () => {
  operationLoading.value = true
  try {
    const params = {
      page: operationPagination.value.current,
      size: operationPagination.value.size,
      ...operationSearchForm.value
    }
    
    const response = await systemLogApi.getOperationLogs(params)
    if (response.data.code === 200) {
      operationLogs.value = response.data.data.records || []
      operationPagination.value.total = response.data.data.total || 0
    } else {
      ElMessage.error(response.data.message || '获取操作日志失败')
    }
  } catch (error) {
    console.error('获取操作日志失败:', error)
    ElMessage.error('获取操作日志失败')
  } finally {
    operationLoading.value = false
  }
}

const searchOperationLogs = () => {
  operationPagination.value.current = 1
  loadOperationLogs()
}

const resetOperationSearch = () => {
  operationSearchForm.value = {
    username: '',
    operation: '',
    status: ''
  }
  operationPagination.value.current = 1
  loadOperationLogs()
}

const handleOperationSizeChange = (size) => {
  operationPagination.value.size = size
  operationPagination.value.current = 1
  loadOperationLogs()
}

const handleOperationCurrentChange = (current) => {
  operationPagination.value.current = current
  loadOperationLogs()
}

// 通用方法
const refreshCurrentTab = () => {
  switch (activeTab.value) {
    case 'upload':
      loadUploadLogs()
      break
    case 'api':
      loadApiLogs()
      break
    case 'operation':
      loadOperationLogs()
      break
  }
}

const clearCurrentLogs = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要清空当前类型的日志吗？此操作不可恢复！',
      '确认清空',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await systemLogApi.clearLogs(activeTab.value)
    if (response.data.code === 200) {
      ElMessage.success('日志清空成功')
      refreshCurrentTab()
    } else {
      ElMessage.error(response.data.message || '日志清空失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('清空日志失败:', error)
      ElMessage.error('日志清空失败')
    }
  }
}

const exportCurrentLogs = async () => {
  try {
    const params = {
      ...(activeTab.value === 'upload' ? uploadSearchForm.value : {}),
      ...(activeTab.value === 'api' ? apiSearchForm.value : {}),
      ...(activeTab.value === 'operation' ? operationSearchForm.value : {})
    }
    
    const response = await systemLogApi.exportLogs(activeTab.value, params)
    
    // 创建下载链接
    const blob = new Blob([response.data], { 
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
    })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    
    const fileName = `${activeTab.value}_logs_${new Date().toISOString().split('T')[0]}.xlsx`
    link.download = fileName
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    
    window.URL.revokeObjectURL(url)
    ElMessage.success('日志导出成功')
  } catch (error) {
    console.error('导出日志失败:', error)
    ElMessage.error('导出日志失败')
  }
}

const deleteLog = async (logId, logType) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这条日志记录吗？',
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await systemLogApi.deleteLog(logId, logType)
    if (response.data.code === 200) {
      ElMessage.success('删除成功')
      refreshCurrentTab()
    } else {
      ElMessage.error(response.data.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除日志失败:', error)
      ElMessage.error('删除日志失败')
    }
  }
}

const getDataTypeLabel = (dataType) => {
  const labels = {
    'income': '收入信息',
    'identity': '身份信息',
    'platform': '平台信息'
  }
  return labels[dataType] || dataType
}

const getDataTypeTagType = (dataType) => {
  const types = {
    'income': 'primary',
    'identity': 'success',
    'platform': 'warning'
  }
  return types[dataType] || 'info'
}

const getStatusLabel = (status) => {
  const labels = {
    0: '处理中',
    1: '处理成功',
    2: '处理失败'
  }
  return labels[status] || '未知'
}

const getStatusTagType = (status) => {
  const types = {
    0: 'warning',
    1: 'success',
    2: 'danger'
  }
  return types[status] || 'info'
}

const showError = (row) => {
  selectedError.value = row
  errorDialogVisible.value = true
}

const showApiDetail = (row) => {
  selectedApi.value = row
  apiDetailDialogVisible.value = true
}

const decryptActiveTab = ref('formatted')

// 检测是否为税务报送请求
const isTaxReportRequest = (requestBody) => {
  if (!requestBody) return false
  
  try {
    const data = JSON.parse(requestBody)
    return data.sjl && data.ywlx && isEncryptedTaxData(data.sjl)
  } catch (error) {
    return false
  }
}

// 解密请求数据
const decryptRequestData = async (requestBody) => {
  try {
    decryptLoading.value = true
    const data = JSON.parse(requestBody)
    
    if (!data.sjl || !data.ywlx) {
      ElMessage.warning('请求数据格式不正确')
      return
    }
    
    const decrypted = await decryptTaxReportData(data.sjl, data.ywlx)
    decryptedContent.value = decrypted
    decryptDialogVisible.value = true
    
    ElMessage.success('数据解密成功')
  } catch (error) {
    console.error('解密失败:', error)
    ElMessage.error('数据解密失败: ' + error.message)
  } finally {
    decryptLoading.value = false
  }
}
// 检测是否为税务报送响应
const isTaxReportResponse = (responseBody) => {
  if (!responseBody) return false

  try {
    const data = JSON.parse(JSON.parse(responseBody).body)
    return data.Response && data.Response.Data && isEncryptedTaxData(data.Response.Data)
  } catch (error) {
    return false
  }
}
// 解密响应数据
const decryptResponseData = async (responseBody) => {
  try {
    decryptLoading.value = true
    const data = JSON.parse(JSON.parse(responseBody).body)

    if (!data.Response || !data.Response.Data) {
      ElMessage.warning('响应数据格式不正确')
      return
    }
    const decrypted = await systemLogApi.getDecrypt(data.Response.Data)
    decryptedContent.value= {
      sjl: JSON.parse(decrypted.data.data),
      isJson: JSON.parse(decrypted.data.data) !== null,
      rawData: data.Response.Data
    }
    decryptResponseDialogVisible.value = true
    ElMessage.success('数据解密成功')
  } catch (error) {
    console.error('解密失败:', error)
    ElMessage.error('数据解密失败: ' + error.message)
  } finally {
    decryptLoading.value = false
  }
}


onMounted(() => {
  loadUploadLogs()
})
</script>

<style scoped>
.system-logs {
  max-width: 1400px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-bar {
  margin-bottom: 20px;
  padding: 10px 0;
}

.search-form {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.el-form-item {
  margin-bottom: 0;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.api-detail h4 {
  margin: 20px 0 10px 0;
  color: #303133;
}

.el-divider {
  margin: 20px 0;
}

.request-actions {
  margin-bottom: 10px;
}

.decrypt-result h4 {
  margin: 20px 0 10px 0;
  color: #303133;
}

.decrypt-result .el-tabs {
  margin-top: 20px;
}

.decrypt-result .el-textarea {
  font-family: 'Courier New', monospace;
  font-size: 12px;
}

.decrypt-result .el-alert {
  margin-bottom: 15px;
}

.decrypt-result .el-descriptions {
  margin-top: 15px;
}
</style>
